from wtforms import  StringField,IntegerField
from wtforms.validators import InputRequired,Email,Length,EqualTo
#在 forms文件中重构了父类，增加了get_errors的方法可以获取到表单的异常信息
from ..forms import BaseForm
from utils import zlcache
from wtforms.validators import ValidationError
from flask import g
from exts import db
from ..cms.models import CMSUser


class LoginForm(BaseForm):
    email = StringField(validators=[Email(message="请输入正确的邮箱"),InputRequired(message="请输入邮箱")])
    password = StringField(validators=[InputRequired(message="请输入密码"),Length(2,20,message="密码的长度是2位到20位")])
    remember = IntegerField()


class ResetPwdForm(BaseForm):
    oldpwd = StringField(validators=[Length(2,20,message="密码的长度是2位到20位")])
    newpwd = StringField(validators=[Length(2,20,message="密码的长度是2位到20位")])
    newpwd_repeat = StringField(validators=[EqualTo("newpwd",message="两次密码不一致")])


class ResetEmailForm(BaseForm):
    email = StringField(validators=[Email(message="请输入正确的邮箱"),InputRequired(message="请输入邮箱")])
    captcha = StringField(validators=[Length(6,6,message="验证码长度不正确")])

    def validate_captcha(self,field):
        captcha = field.data
        email = self.email.data
        captcha_cache = zlcache.get(email)
        # print(captcha, email,captcha_cache)
        if not captcha_cache or captcha_cache.lower() != captcha.lower():
            raise ValidationError("邮箱验证码错误")

    def validate_email(self,field):
        email = field.data
        user = g.cms_user
        user1 = CMSUser.query.filter(CMSUser.email==email).first()
        if email == user.email:
            raise ValidationError("不能修改成相同的邮箱!")
        elif user1:
            raise ValidationError("新邮箱已经被注册了")


class BannerForm(BaseForm):
    name = StringField(validators=[InputRequired(message="请输入轮播图名字")])
    image_url = StringField(validators=[InputRequired(message="请输入轮播图链接")])
    link_url = StringField(validators=[InputRequired(message="请输入轮播图跳转链接")])
    priority = StringField(validators=[InputRequired(message="请输入轮播图优先级")])


class UpdateBannerForm(BannerForm):
    banner_id = StringField(validators=[InputRequired(message="请输入轮播图id")])

class AddBoardForm(BaseForm):
    name = StringField(validators=[InputRequired(message="请输入模块名")])

class UpdateBoardForm(AddBoardForm):
    board_id = StringField(validators=[InputRequired(message="请输入模块id")])